package com.jxd.ordering.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jxd.ordering.dao.OrderMapper;
import com.jxd.ordering.model.Order;
import com.jxd.ordering.service.IDictService;
import com.jxd.ordering.service.IOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @ClassName OrderServiceImpl
 * @Description TODO
 * @Author Ankailong
 * @Date 2022/9/30
 * @Version 1.0
 */
@Service
public class OrderServiceImpl implements IOrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private IDictService dictService;

    @Override
    public boolean addOrder(Order order) {
        return orderMapper.insertOrder(order);
    }

    @Override
    public boolean editOrder(Order order) {
        return orderMapper.updateOrder(order);
    }

    @Override
    public boolean editOrderStatu(int orderno, int statu) {
        return orderMapper.updateOrderStatu(orderno, statu);
    }

    @Override
    public boolean delOrder(int[] ordernos) {
        return orderMapper.deleteOrder(ordernos);
    }

    @Override
    public Map<String, Object> getOrderPyPage(Map<String, String> queryMap) {
        String page = queryMap.get("page");
        String limit = queryMap.get("limit");

        Map<String, Object> map = new HashMap(4);
        if(page != null && limit != null){
            IPage<Order> pages = new Page(Integer.parseInt(page),Integer.parseInt(limit));
            orderMapper.selectOrderByPage(pages, queryMap);

            map.put("count",pages.getTotal());
            map.put("data",pages.getRecords());

            ((List<Map<String, Object>>) (map.get("data"))).stream().map(item -> {
                if (item.get("type") != null) {
                    item.put("type", dictService.getDict("type", item.get("type").toString()));
                }
                if (item.get("statu") != null) {
                    item.put("statu", dictService.getDict("statu", item.get("statu").toString()));
                }
                return item;
            }).collect(Collectors.toList());

            map.put("code",0);
            return map;
        }else{
            map.put("data", (Object)null);
            map.put("code", "500");
            map.put("msg", "参数不符");
            map.put("count", (Object)null);
            return map;
        }
    }

    @Override
    public Order getOrderByOrderno(int orderno) {
        return orderMapper.selectOrderByOrderno(orderno);
    }

    @Override
    @Transactional
    public boolean editOrderEmp(int orderno, int[] after) {
        //开启事务
        List<Integer> add = new ArrayList<>();
        List<Integer> del = new ArrayList<>();
        List<Integer> before = orderMapper.selectAllOrderEmp(orderno);

        /*//修改前的订餐人员中没有empno，则添加
        for (int empno : after) {
            if (before.indexOf((Integer)empno) < 0) {
                add.add(empno);
            }
        }
        //修改后的订餐人员中没有empno，则删除
        for (int empno : before) {
            if (Arrays.binarySearch(after, empno) < 0) {
                del.add(empno);
            }
        }*/

        //before：修改前订单订餐人员列表
        //after：修改后订单订餐人员列表
        int p1 = 0, p2 = 0;
        while (p1 < before.size() && p2 < after.length) {
            if (before.get(p1) < after[p2]) {
                //after中没有before中p1位置的元素，则删除
                del.add(before.get(p1++));
            } else if (before.get(p1) == after[p2]) {
                p1++;
                p2++;
            } else {
                //before中没有after中p2位置的元素，则添加
                add.add(after[p2++]);
            }
        }
        while (p1 < before.size()) {
            del.add(before.get(p1++));
        }
        while (p2 < after.length) {
            add.add(after[p2++]);
        }

        if (add.size() > 0) {
            orderMapper.insertOrderEmp(orderno, add.stream().mapToInt(Integer::intValue).toArray());
        }
        if (del.size() > 0) {
            orderMapper.deleteOrderEmp(orderno, del.stream().mapToInt(Integer::intValue).toArray());
        }
        return true;
    }

    @Override
    @Transactional
    public boolean editOrderMeal(int orderno, Map<String, Map<String, String>> meals) {
        //开启事务
        List<Integer> add = new ArrayList<>();
        List<Integer> edit = new ArrayList<>();
        List<Integer> del = new ArrayList<>();
        Map<String, Map<String, Object>> a = getAllOrderMeal(orderno);
        List<Integer> before = new ArrayList<>(getAllOrderMeal(orderno).keySet()).stream().map(Integer::parseInt).collect(Collectors.toList());//修改前订单餐品编号列表
        List<Integer> after = new ArrayList<>(meals.keySet()).stream().map(Integer::parseInt).collect(Collectors.toList());//修改后订单餐品编号列表

        //before：修改前订单订餐人员列表
        //after：修改后订单订餐人员列表
        int p1 = 0, p2 = 0;
        while (p1 < before.size() && p2 < after.size()) {
            if (before.get(p1) < after.get(p2)) {
                //after中没有before中p1位置的元素，则删除
                del.add(before.get(p1++));
            } else if (before.get(p1).equals(after.get(p2))) {
                edit.add(before.get(p1));
                p1++;
                p2++;
            } else {
                //before中没有after中p2位置的元素，则添加
                add.add(after.get(p2++));
            }
        }
        while (p1 < before.size()) {
            del.add(before.get(p1++));
        }
        while (p2 < after.size()) {
            add.add(after.get(p2++));
        }

        for (String key : meals.keySet()) {
            meals.get(key).put("orderno", String.valueOf(orderno));
            meals.get(key).put("mealno", key);
        }
        /*for (Integer mealno : add) {
            orderMapper.insertOrderMeal(meals.get(String.valueOf(mealno)));
        }
        for (int mealno : edit) {
            orderMapper.updateOrderMeal(meals.get(String.valueOf(mealno)));
        }*/
        if (add.size() > 0) {
            orderMapper.insertOrderMeal(meals.values().stream().filter(item -> add.contains(Integer.parseInt(item.get("mealno")))).collect(Collectors.toList()));
        }
        if (edit.size() > 0) {
            System.out.println(meals.values().stream().filter(item -> edit.contains(Integer.parseInt(item.get("mealno")))).collect(Collectors.toList()));
            List<String> fields = new ArrayList<>();
            fields.add("count");
            fields.add("remark");
            orderMapper.updateOrderMeal(orderno ,meals.values().stream().filter(item -> edit.contains(Integer.parseInt(item.get("mealno")))).collect(Collectors.toList()), fields);
        }
        if (del.size() > 0) {
            orderMapper.deleteOrderMeal(orderno, del.stream().mapToInt(Integer::intValue).toArray());
        }
        return true;
    }

    @Override
    public Map<String, Object> getOrderMealByMealno(int orderno, int mealno) {
        Map<String, Object> map = orderMapper.selectOrderMeal(orderno, mealno);
        map.put("prices", Integer.parseInt(map.get("count").toString()) * Double.parseDouble(map.get("price").toString()));
        return map;
    }

    @Override
    public List<Map<String, String>> getAllOrderEmp(int orderno) {
        return orderMapper.getAllOrderEmp(orderno);
    }

    @Override
    public Map<String, Map<String, Object>> getAllOrderMeal(int orderno) {
        List<Map<String, Object>> list = orderMapper.selectAllOrderMeal(orderno);
        Map<String, Map<String, Object>> map = new HashMap<>();

        for (Map<String, Object> meal : list) {
            meal.put("prices", Integer.parseInt(meal.get("count").toString()) * Double.parseDouble(meal.get("price").toString()));
            map.put(String.valueOf(meal.get("mealno")), meal);
        }

        return map;
    }
}
